package cn.zdm.authserver.config.authentication;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * copyright (C), 2021, 北京同创永益科技发展有限公司
 *
 * @author ZhaoDeman
 * @version 1.0.0
 * <author>                <time>                  <version>                   <description>
 * ZhaoDeman        2021/1/6 14:02                 1.0
 * @program auth-server
 * @description LoginSuccessHandler 当我们登录成功时，处理的handler
 * @create 2021/1/6 14:02
 */
@Slf4j
public class SecurityAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    /**
     * login 登录成功的请求逻辑
     *
     * @param request        http request请求
     * @param response       response 请求
     * @param chain          Filter过滤连
     * @param authentication 身份认证的类
     * @throws IOException      IO异常
     * @throws ServletException Servlet 异常
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        FilterChain chain, Authentication authentication) throws IOException, ServletException {
        log.info("请求方法====>{}", request.getMethod());
        log.info("登录成功====>{}", request.getHeader("accept"));
        if (request.getHeader("accept").contains("application/json")) {
            response.setContentType("application/json;charset=UTF-8");
            log.info("登录成功====>{}");
            PrintWriter out = response.getWriter();
            out.write("{\"error_code\":\"0\", \"message\":\"欢迎登录系统\"}");
        } else {
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}
